import java.io.*;
import java.beans.*;

public class Salesman implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9088127018019084994L;
	protected boolean busy;
	protected Product offeredProduct;
	protected PropertyChangeSupport aCS = new PropertyChangeSupport(this);
	

	public Salesman() {
		busy = false;
		System.out.println("Salesman: Neuer Salesman erstellt");
	}

	public boolean isBusy() {
		System.out.println("Salesman: isBusy");
		return busy;
	}

	public void setBusy(boolean busy) {
		System.out.println("Salesman: setBusy "+busy);
		synchronized (this) {
			boolean oldMode = this.busy;
			if (oldMode != busy) {
				this.busy = busy;
				aCS.firePropertyChange("busy", new Boolean(oldMode),
						new Boolean(this.busy));
			}
		}
	}

	public void setOfferedProduct(Product p) {
		System.out.println("Salesman: setOfferedProduct " + p.getArticle().getName());
		offeredProduct = p;
	}

	public void addPropertyChangeListener(PropertyChangeListener bosses) {
		aCS.addPropertyChangeListener(bosses);
	}

	public void removePropertyChangeListener(PropertyChangeListener bosses) {
		aCS.removePropertyChangeListener(bosses);
	}

	public void sell(Customer cust) {
		System.out.println("Salesman: sell ");

		try {
			cust.pay(offeredProduct.getPrice());
		} catch (PropertyVetoException e) {
			String msg = e.toString();

			System.out
					.println("Salesman: 'Sorry, you cannot buy this since your bank told me: "
							+ msg.substring(msg.indexOf(' ') + 1) + "'");
			return;
		}
		offeredProduct.setSold(true);
		System.out.println("Salesman: 'Here you are. Have fun!'");
		setBusy(false);
	}

	public int askForProduct(String name) throws NotAvailable {
		System.out.println("Salesman: askForProduct "+name);
		
		if (!name.equals(offeredProduct.getArticle().getName()))
			throw new NotAvailable("Not in stock");
		if(offeredProduct.isSold()) throw new NotAvailable("Product is sold out");
		offeredProduct.setReserved(true);
		return offeredProduct.getPrice();
	}
	public void setBoss(PropertyChangeListener prop){
		this.addPropertyChangeListener(prop);
	}
}
